package net.meblabs.bookapp.web.controller;

import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.meblabs.bookapp.data.dao.AuthorDao;
import net.meblabs.bookapp.data.model.Author;
import net.meblabs.bookapp.util.Message;
import net.meblabs.bookapp.util.Message.MessageType;
import net.meblabs.bookapp.util.MessagePropertyEditor;
import net.meblabs.bookapp.util.ServiceLoaderUtil;
import net.meblabs.bookimp.AuthorImporter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping("/author")
public class AuthorController {

	@Autowired
	private AuthorDao authorDao;

	@InitBinder
	public void init(WebDataBinder binder) {
		binder.registerCustomEditor(Message.class, new MessagePropertyEditor());
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView authors() {
		List<Author> authors = authorDao.find();
		Collection<AuthorImporter> importers = ServiceLoaderUtil.load(AuthorImporter.class);
		ModelAndView mav = new ModelAndView("authors");
		mav.addObject("authors", authors);
		mav.addObject("importers", importers);
		mav.addObject("author", new Author());
		return mav;
	}

	@RequestMapping("/{id}")
	public String author(@PathVariable("id") Long id, Model model) {
		Author author = authorDao.findById(id);
		model.addAttribute("author", author);
		return "author";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView authorSaveForm(@Valid @ModelAttribute("author") Author author,
			BindingResult result) {
		boolean error = false;
		Message message;
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		if (result.hasErrors()) {
			error = true;
			message = new Message(MessageType.ERROR, "Wystapiły błędy przy zapisie ("
					+ result.getErrorCount() + ")");
		} else {
			try {
				authorDao.save(author);
				message = new Message(MessageType.INFO, "Zapisano");
			} catch (Exception e) {
				message = new Message(MessageType.ERROR, "Wystapiły błędy przy zapisie: "
						+ e.getMessage());
				error = true;
			}
		}

		ModelAndView mav;
		if (error) {
			mav = new ModelAndView("templates/authorSaveForm");
		} else {
			mav = new ModelAndView(new RedirectView("/author/save", true) {
				@Override
				protected boolean isEligibleProperty(String key, Object value) {
					if (value instanceof Message) {
						return true;
					} else {
						return super.isEligibleProperty(key, value);
					}
				}
			});
		}
		mav.addObject("message", message);
		return mav;
	}

	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public ModelAndView authorSaveForm(@ModelAttribute("author") Author author,
			@RequestParam(value = "message", required = false) Message message,
			HttpServletRequest req) {
		ModelAndView mav = new ModelAndView("templates/authorSaveForm");
		mav.addObject("message", message);
		return mav;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView authorsList() {
		List<Author> authors = authorDao.find();
		ModelAndView mav = new ModelAndView("templates/authorsList");
		mav.addObject("authors", authors);
		return mav;
	}

	@RequestMapping(value = "/aa", method = RequestMethod.GET)
	public @ResponseBody
	String aa(HttpServletRequest req, HttpServletResponse resp) {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		return "ąśżźćńłóę";
	}
}
